# coding:utf-8
# Author : hiicy redldw
# Date : 2019/05/06
import tensorflow as tf
import functools
import pandas as pd

def trainInputFn(features, labels, batch_size,epoch):
    dataset = tf.data.Dataset.from_tensor_slices((dict(features),labels))
    ds = dataset.shuffle(1000).repeat(epoch).batch(batch_size)
    # 生成批次(features, labels)对的输入管道
    iteror = ds.make_one_shot_iterator()
    return iteror.get_next()

def myModelFn(features,labels,mode,params):
    """
    :param features: This is batch_features from input_fn
    :param labels:This is batch_features from input_fn
    :param mode:An instance of tf.estimator.ModeKeys
    :param params:Additional configuration
    :return:
    """
    input_layer = tf.reshape(features,[-1,224,224,3])

    x = tf.layers.conv2d(
        inputs=input_layer,
        filters=32,
        kernel_size=(3,3),
        padding='same',
        activation=tf.nn.relu
    )
    pool2 = tf.layers.max_pooling2d(inputs=x, pool_size=[2, 2], strides=2)

    x = tf.reshape(pool2,(-1,112*112*32))
    dropout = tf.layers.dropout(
        inputs=x, rate=0.4, training=mode == tf.estimator.ModeKeys.TRAIN)
    logits = tf.layers.dense(inputs=dropout, units=8, activation=tf.nn.relu)
    predictions = {
        # Generate predictions (for PREDICT and EVAL mode)
        "classes": tf.argmax(input=logits, axis=1),
        # Add `softmax_tensor` to the graph. It is used for PREDICT and by the
        # `logging_hook`.
        "probabilities": tf.nn.softmax(logits, name="softmax_tensor")
    }

    if mode == tf.estimator.ModeKeys.PREDICT:
        return tf.estimator.EstimatorSpec(mode=mode, predictions=predictions)

    # Calculate Loss (for both TRAIN and EVAL modes)
    loss = tf.losses.sparse_softmax_cross_entropy(labels=labels, logits=logits)

    # Configure the Training Op (for TRAIN mode)
    if mode == tf.estimator.ModeKeys.TRAIN:
        optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.001)
        # REW:global_step全局步数几乎都跟loss一起用
        train_op = optimizer.minimize(
            loss=loss,
            global_step=tf.train.get_global_step())
        return tf.estimator.EstimatorSpec(mode=mode, loss=loss, train_op=train_op)

    # Add evaluation metrics (for EVAL mode)
    eval_metric_ops = {
        "accuracy": tf.metrics.accuracy(
            labels=labels, predictions=predictions["classes"])}
    return tf.estimator.EstimatorSpec(
        mode=mode, loss=loss, eval_metric_ops=eval_metric_ops)

if __name__ == "__main__":
    totals = 150528
    columns = []
    for i in range(totals):
        columns.append(f'pixel{i + 1}')
    columns.append('label')
    ckptPath = r'F:\Resources\backup\fatp'
    myModel = tf.estimator.Estimator(
        model_fn=myModelFn,
        model_dir=ckptPath,
        params={
            'classes':8
        }
    )
    csvFile = r"F:\Resources\backup\img.csv"
    # TODO:csv 行解析器
    trainDf = pd.read_csv(csvFile,header=None,names=columns,skiprows=1)
    label=trainDf.pop("label")
    print(trainDf.head())
    print('read data done')
    # 这是一种定义输入函数就把数据也传输了

    trainInputFn = functools.partial(trainInputFn,features={"img":trainDf},
                                     labels=label,
                                     batch_size=32,
                                     epoch=5)
    print('train input funcion done')
    myModel.train(
        input_fn=trainInputFn,
    )